<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .box {
            width: 200px;
            height: 200px;
            background-color: #6ff;
            margin: 50px;
        }
    </style>
</head>

<body>
    <div class="box"></div>
</body>
<script>
    var box = document.getElementsByClassName("box")[0];

    // 问题: 函数嵌套调用过程中,会出现多个this指向,this指向冲突  
    // 解决方法1:
    // 1. 提前声明中间变量(_this  that) 存储this指向


    // 封装一个函数  传入一个元素,给该元素绑定点击事件, 点击时随机颜色;
    var obj = {
        ele: box,
        bindEvent: function () {  //绑定点击事件
            // this -> obj
            console.log("bindEvenet:", this);
            var _this = this;  // _this也引用obj

            this.ele.addEventListener("click", function () {
                // this -> 绑定事件的元素 (box)
                console.log("click", this, _this);
                this.style.backgroundColor = _this.randColor();
            })

        },
        randColor: function () {
            var colorStr = "0123456789abcdef";
            var str = "#";
            for (var i = 0; i < 6; i++) {
                var index = Math.floor(Math.random() * colorStr.length); // 0-15
                var char = colorStr.charAt(index);
                // console.log(num,char);
                str += char;
            }
            console.log(str);
            return str;
        }
    }

    obj.bindEvent();
</script>

</html>